package services

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"io"
	"log"
	"net/http"
	"regexp"
	"strconv"
	"strings"
	"time"
	"wecom_rebot/common"
	"wecom_rebot/core"
	"wecom_rebot/models"
)

var oeBindBatchTxLogger *logrus.Logger

// InitOeBindBatchLogger 移除 init() 函数，改为显式初始化函数
func InitOeBindBatchLogger() {
	// 确保在 common 初始化后调用
	oeBindBatchTxLogger = core.InitLogger(common.LogsErrorMap[9])
}

type OeBindBatchService struct{}

// AnalyzeContentResult 定义解析内容的结构体
type AnalyzeContentResult struct {
	AccountIDs   []string
	PersonCharge string
	Collaborator []string
	Table        string
}

type AssignAdvListResponseData struct {
	SuccessAdvList []SuccessAdvItem `json:"successAdvList"`
	FailAdvIds     []interface{}    `json:"failAdvIds"`
}

type SuccessAdvItem struct {
	AdvId         int64         `json:"advId"`
	AdvName       string        `json:"advName"`
	OptimizerId   int64         `json:"optimizerId"`
	OptimizerName string        `json:"optimizerName"`
	Collaborator  []interface{} `json:"collaborator"`
}

type oeBindBatchCurlResponse struct {
	Code int                       `json:"code"`
	Data AssignAdvListResponseData `json:"data"` // 修改为具体结构体
	Msg  string                    `json:"msg"`
}

// AssignBatchPackage 定义请求数据结构体
type AssignBatchPackage struct {
	AdvId           int64    `json:"advId"`
	OptimizerId     string   `json:"optimizerId"`
	CollaboratorIds []string `json:"collaboratorIds"`
}

type PostData struct {
	AssignType     string               `json:"assignType"`
	AssignSource   string               `json:"assignSource"`
	AssignTarget   string               `json:"assignTarget"`
	AssignPackages []AssignBatchPackage `json:"assignPackages"`
}

// AdvResult 使用嵌套结构体保持与JSON结构一致
type AdvResult struct {
	AdvId   int64  `json:"advId"`
	Success bool   `json:"success"`
	Msg     string `json:"msg"`
}

// 修改 confirmResponse 定义
type confirmResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		AdvResultList  []AdvResult `json:"advResultList"`
		TotalAdvIdsNum int         `json:"totalAdvIdsNum"`
		ErrorAdvIdsNum int         `json:"errorAdvIdsNum"`
	} `json:"data"`
}

func (s *OeBindBatchService) Handle(msgId int, subjectName, roomId string, content []string, jobId uint64) error {
	var msg = &models.Msg{}

	fmt.Println("oeBindBatchTxLogger", "原始结构Id：", msgId)
	// 获取数据
	err := common.DB.Where("id = ?", msgId).First(&msg).Error
	if err != nil {
		oeBindBatchTxLogger.Error("巨量批量绑定销售获取数据失败", common.LogsErrorMap[2], msgId, err)
		return err
	}

	oeBindBatchTxLogger.Info("oeBindBatchTxLogger", "原始结构：", content)

	// 处理需要的数据结构
	result, err := s.analyzeContent(content)
	if err != nil {
		oeBindBatchTxLogger.Error(err)
		return err
	}

	// 移除功能行
	msg.Content = RemoveTitle(msg)
	fmt.Println("oeBindBatchTxLogger", result, "移除后的结构：", msg, "广告主信息：", content)

	rdb := core.InitRedis(13)
	ctx := context.Background()

	cookies, err := rdb.Get(ctx, "laravel_database_oead_adv_cookies").Result()
	token, err := rdb.Get(ctx, "laravel_database_oead_adv_cg_csrf_token").Result()

	fmt.Println("oeBindBatchTxLogger", "Cookies:", cookies, "tk:", token)

	// 查询任务
	var job models.Job
	if err = common.DB.Where("id = ?", jobId).First(&job).Error; err != nil {
		oeBindBatchTxLogger.Error("查询完整任务记录", common.LogsErrorMap[2], jobId, err)
		return err
	}

	// 将广告账户ID分割为480个一组
	accountIDs := result.AccountIDs
	accountChunks := chunkStrings(accountIDs, 480)

	// 打印调试信息
	oeBindBatchTxLogger.Infof("分割后的广告账户ID块: %v", accountChunks)
	// 查找失败负责人邮箱
	var errorPersonCharge []string

	// 统计失败协作人邮箱
	var errorCollaborator []string

	// 统计绑定成功
	var successCollaborator []string

	// 统计绑定失败
	errorBindUser := make(map[string]interface{})

	for _, chunk := range accountChunks {
		// 处理责任人
		var collaboratorIDs []string

		// 获取责任人信息
		agentPersonCharge, err := s.GetAgentSale(result.PersonCharge, cookies)
		if err != nil {
			oeBindBatchTxLogger.Errorf("获取负责人失败: %v", err)
			return fmt.Errorf("获取负责人失败: %w", err)
		}

		optimizerID := agentPersonCharge.AgentID

		// 获取协作者信息
		for _, collaborator := range result.Collaborator {
			agentCollaborator, err := s.GetAgentSale(collaborator, cookies)
			if err != nil {
				oeBindBatchTxLogger.Errorf("获取协作者失败: %v", err)
				return fmt.Errorf("获取协作者失败: %w", err)
			}
			collaboratorIDs = append(collaboratorIDs, agentCollaborator.AgentID)
		}

		// 如果为空直接跳出这个循环
		if len(chunk) == 0 {
			continue
		}

		// 在 accountChunks 循环中添加
		information, err := s.AssignAdvList(chunk, msg, cookies, token)
		if err != nil {
			oeBindBatchTxLogger.Errorf("获取指定账户ID记录失败: %v", err)
			if information != nil {
				return fmt.Errorf("获取协作者失败: %w, 信息：%v", err, information["msg"])
			}
			break
		}
		oeBindBatchTxLogger.Infof("获取指定账户ID记录: %v", information)

		dataList := make([]interface{}, 0)
		if data, ok := information["data"]; ok {
			// 尝试不同的类型转换
			switch v := data.(type) {
			case []SuccessAdvItem:
				// 转换为[]interface{}
				dataList = make([]interface{}, len(v))
				for i, item := range v {
					dataList[i] = item
				}
			case []interface{}:
				dataList = v
			}
		}

		if len(dataList) == 0 {
			log.Printf("data字段为空或类型不匹配")
			continue
		}

		assignPackages, err := s.buildAssignPackages(dataList, collaboratorIDs, optimizerID)
		if err != nil {
			oeBindBatchTxLogger.Warn("构建分配包失败")
			return errors.New("构建分配包失败")
		}

		// 构建最终请求体
		postData := PostData{
			AssignType:     "AVERAGE",
			AssignSource:   "BIDDING",
			AssignTarget:   "ALL",
			AssignPackages: assignPackages,
		}

		oeBindBatchTxLogger.Info("发送给巨量组合数据", postData)

		confirmResult, err := s.optimizerCollaborators(postData, msg, cookies, token)
		if err != nil {
			oeBindBatchTxLogger.Warnf("绑定请求失败: %v", err)
			errorBindUser[err.Error()] = struct{}{}
			continue
		}
		// 记录返回数据
		oeBindBatchTxLogger.Infof("巨量返回成功数据: %+v", confirmResult.Data.AdvResultList)

		// 处理返回结果
		for _, resultItem := range confirmResult.Data.AdvResultList {
			if resultItem.Success && resultItem.Msg == "执行成功" {
				// 统计成功绑定
				successCollaborator = append(successCollaborator, strconv.FormatInt(resultItem.AdvId, 10))
			} else {
				// 记录绑定失败
				errorKey := resultItem.Msg
				if _, ok := errorBindUser[errorKey]; !ok {
					errorBindUser[errorKey] = []string{}
				}
				errorBindUser[errorKey] = append(
					errorBindUser[errorKey].([]string),
					strconv.FormatInt(resultItem.AdvId, 10),
				)
			}
		}
	}

	// 在 Handle 方法末尾添加以下代码
	// 处理成功绑定
	if len(successCollaborator) > 0 {
		var successMsg string
		successCount := len(successCollaborator)
		maxDisplay := 50 // 设置最大显示数量

		if successCount > maxDisplay {
			// 截断处理
			truncated := successCollaborator[:maxDisplay]
			remaining := successCount - maxDisplay
			successMsg = fmt.Sprintf("%s\n因聊天框内容限制，其余 %d 个账户未显示。",
				strings.Join(truncated, ","), remaining)
		} else {
			successMsg = strings.Join(successCollaborator, ",")
		}

		// 发送成功消息
		sendErr := BendiSendText(
			fmt.Sprintf("%s\n-----------------------------------\n绑定成功的账户：%s",
				msg.Content, successMsg),
			msg.RoomID, msg.Sender)
		if sendErr != nil {
			oeBindBatchTxLogger.Errorf("发送成功消息失败: %v", sendErr)
		}
	}

	// 处理错误绑定
	if len(errorBindUser) > 0 {
		var errorMessages []string

		// 遍历错误信息
		for errorKey, errorList := range errorBindUser {
			// 类型断言检查
			if ids, ok := errorList.([]string); ok {
				errorMessages = append(errorMessages,
					fmt.Sprintf("%s：%s", errorKey, strings.Join(ids, ",")))
			}
		}

		// 发送错误消息
		if len(errorMessages) > 0 {
			sendErr := BendiSendText(
				fmt.Sprintf("%s\n-----------------------------------\n%s",
					msg.Content, strings.Join(errorMessages, "\n")),
				msg.RoomID, msg.Sender)
			if sendErr != nil {
				oeBindBatchTxLogger.Errorf("发送错误消息失败: %v", sendErr)
			}
		}
	}

	// 处理负责人未找到
	if len(errorPersonCharge) > 0 {
		sendErr := BendiSendText(
			fmt.Sprintf("%s\n-----------------------------------\n巨量后台未找到负责人邮箱对应的账户：%s",
				msg.Content, strings.Join(errorPersonCharge, ",")),
			msg.RoomID, msg.Sender)
		if sendErr != nil {
			oeBindBatchTxLogger.Errorf("发送负责人错误消息失败: %v", sendErr)
		}
	}

	// 处理协作者未找到
	if len(errorCollaborator) > 0 {
		sendErr := BendiSendText(
			fmt.Sprintf("%s\n-----------------------------------\n巨量后台未找到协作者邮箱对应的账户：%s",
				msg.Content, strings.Join(errorCollaborator, ",")),
			msg.RoomID, msg.Sender)
		if sendErr != nil {
			oeBindBatchTxLogger.Errorf("发送协作者错误消息失败: %v", sendErr)
		}
	}
	return nil
}

func (s *OeBindBatchService) optimizerCollaborators(data PostData, msg *models.Msg, oeAdCookies, oeCsrfToken string) (*confirmResponse, error) {
	url := "https://agent.oceanengine.com/agent/assign-adv/assign/optimizer-collaborators-v3"

	var confirm confirmResponse
	err := s.SendCurlRequest(url, data, oeAdCookies, "POST", oeCsrfToken, &confirm)
	if err != nil {
		// 记录错误日志
		oeBindBatchTxLogger.Infof("optimizer_collaborators请求失败: %v", err)

		// 发送错误消息
		sendErr := BendiSendText(
			msg.Content+"\n-----------------------------------\n"+"获取数据失败！"+confirm.Msg,
			msg.RoomID,
			msg.Sender,
		)
		if sendErr != nil {
			return nil, fmt.Errorf("消息发送失败: %w", sendErr)
		}

		return nil, fmt.Errorf("请求发送失败: %w", err)
	}

	oeBindBatchTxLogger.Infof("optimizer_collaborators记录curl请求信息: %v", confirm)

	// 检查返回码不为0的情况
	if confirm.Code != 0 {
		oeBindBatchTxLogger.Infof("optimizer_collaborators记录curl请求信息code != 0：%v", confirm)
		err := BendiSendText(msg.Content+"\n-----------------------------------\n"+"绑定账号失败！"+confirm.Msg, msg.RoomID, msg.Sender)
		if err != nil {
			return nil, err
		}
		return nil, fmt.Errorf("接口返回错误: %s", confirm.Msg)
	}

	// 检查advResultList为空的情况
	if len(confirm.Data.AdvResultList) == 0 {
		oeBindBatchTxLogger.Infof("optimizer_collaborators记录curl请求信息success != true：%v", confirm)
		err := BendiSendText(msg.Content+"\n-----------------------------------\n"+"绑定账号失败！"+confirm.Msg, msg.RoomID, msg.Sender)
		if err != nil {
			return nil, err
		}
		return nil, fmt.Errorf("返回数据为空: %s", confirm.Msg)
	}

	// 返回成功结果
	return &confirm, nil
}

// 转换核心逻辑
func (s *OeBindBatchService) buildAssignPackages(dataList []interface{}, collaboratorIDs []string, optimizerID string) ([]AssignBatchPackage, error) {
	var assignBatchPackages []AssignBatchPackage

	for _, item := range dataList {
		// 处理不同的数据类型
		var itemMap map[string]interface{}

		// 如果item本身就是SuccessAdvItem结构体
		if successItem, ok := item.(SuccessAdvItem); ok {
			// 将SuccessAdvItem转换为map[string]interface{}
			itemMap = map[string]interface{}{
				"advId":         float64(successItem.AdvId),
				"advName":       successItem.AdvName,
				"optimizerId":   successItem.OptimizerId,
				"optimizerName": successItem.OptimizerName,
				"collaborator":  successItem.Collaborator,
			}
		} else if m, ok := item.(map[string]interface{}); ok {
			// 如果item是map[string]interface{}
			itemMap = m
		} else {
			// 类型不匹配，跳过该项
			continue
		}

		// 提取基础字段
		var advId int64
		switch v := itemMap["advId"].(type) {
		case float64:
			advId = int64(v)
		case int64:
			advId = v
		case int:
			advId = int64(v)
		default:
			continue // 无法处理的类型，跳过
		}

		// 提取协作者ID
		var idArr []string
		if collabData, ok := itemMap["collaborator"]; ok && collabData != nil {
			// 处理不同类型的协作者数据
			switch collabList := collabData.(type) {
			case []interface{}:
				// 如果是[]interface{}类型
				for _, c := range collabList {
					switch v := c.(type) {
					case string:
						// 如果是字符串，直接使用
						idArr = append(idArr, v)
					case map[string]interface{}:
						// 如果是对象，提取id字段
						if id, ok := v["id"].(string); ok {
							idArr = append(idArr, id)
						}
					}
				}
			case []SuccessAdvItem:
				// 如果是[]SuccessAdvItem类型（不太可能，但为了完整性）
				// 这种情况下可能需要不同的处理方式
			}
		}

		// 合并并去重
		mergeMap := make(map[string]bool)
		for _, id := range idArr {
			mergeMap[id] = true
		}
		for _, id := range collaboratorIDs {
			mergeMap[id] = true
		}

		// 构建结果
		assignBatchPackages = append(assignBatchPackages, AssignBatchPackage{
			AdvId:           advId,
			OptimizerId:     optimizerID,
			CollaboratorIds: toStringSlice(mergeMap),
		})
	}

	if len(assignBatchPackages) == 0 {
		return nil, fmt.Errorf("未生成有效的分配包")
	}

	return assignBatchPackages, nil
}

// GetAgentSale 获取代理销售信息
func (s *OeBindBatchService) GetAgentSale(email string, oeAdCookies string) (*AgentInfo, error) {
	// 构造请求URL
	url := "https://bsm.oceanengine.com/apps/bsm_web/back_end/agent/list/"

	// 构造POST数据
	postData := map[string]interface{}{
		"pageNo":      1,
		"page":        1,
		"pageSize":    10,
		"filters":     map[string]string{"nameOrEmail": email},
		"sorter":      []interface{}{},
		"nameOrEmail": email,
	}

	// 发送POST请求
	var response oeBindSaleCurlResponse
	err := s.SendCurlRequest(url, postData, oeAdCookies, "POST", "", &response)
	if err != nil {
		oeBindSaleTxLogger.Infof("get_agent_sale请求失败: %v", err)
		return nil, fmt.Errorf("查询代理销售失败: %v", err)
	}

	// 记录完整响应
	oeBindSaleTxLogger.Infof("get_agent_sale记录curl请求信息: %v", response)

	// 检查响应码
	if response.Code != 1 {
		oeBindSaleTxLogger.Infof("get_agent_sale请求错误: %v", response)
		return nil, fmt.Errorf("接口返回错误: %s", response.Msg)
	}

	// 解析响应数据
	var responseData map[string]interface{}
	switch v := response.Data.(type) {
	case map[string]interface{}:
		responseData = v
	case map[interface{}]interface{}:
		// 转换 map[interface{}]interface{} 为 map[string]interface{}
		responseData = make(map[string]interface{})
		for k, val := range v {
			if kStr, ok := k.(string); ok {
				responseData[kStr] = val
			}
		}
	default:
		return nil, fmt.Errorf("第一个接口响应数据格式错误: 期望 map 类型，实际类型是 %T，值: %+v", response.Data, response.Data)
	}

	// 获取data数组
	dataArray, ok := responseData["data"].([]interface{})
	if !ok || len(dataArray) == 0 {
		oeBindSaleTxLogger.Infof("get_agent_sale查询不到代理销售信息: %s", email)
		return nil, fmt.Errorf("未找到代理销售数据")
	}

	// 获取第一个数据项
	item, ok := dataArray[0].(map[string]interface{})
	if !ok {
		return nil, fmt.Errorf("数据项格式错误")
	}

	// 提取字段
	agentID, _ := item["id"].(float64)
	agentName, _ := item["name"].(string)

	// 返回结果
	return &AgentInfo{
		AgentID:   strconv.Itoa(int(agentID)),
		AgentName: agentName,
	}, nil
}

// AssignAdvList 获取指定账户ID记录
func (s *OeBindBatchService) AssignAdvList(accountID []string, msg *models.Msg, oeAdCookies, oeCsrfToken string) (map[string]interface{}, error) {
	url := "https://agent.oceanengine.com/agent/assign-adv/validate/assign-adv-list"

	postData := map[string]interface{}{
		"advIds":       accountID,
		"assignSource": "BIDDING",
	}

	// 发送请求
	var responseListData oeBindBatchCurlResponse
	err := s.SendCurlRequest(url, postData, oeAdCookies, "POST", oeCsrfToken, &responseListData)
	if err != nil {
		oeBindBatchTxLogger.Infof("assign_adv_list请求失败: %v", err)
		return map[string]interface{}{
			"code": 1,
			"msg":  err.Error(),
		}, err
	}

	// 记录响应
	oeBindBatchTxLogger.Infof("assign_adv_list记录curl请求信息：%v", responseListData)

	// 检查响应码
	if responseListData.Code != 0 {
		oeBindBatchTxLogger.Infof("assign_adv_list请求错误：%v", responseListData)
		return map[string]interface{}{
			"code": 1,
			"msg":  responseListData.Msg,
		}, fmt.Errorf(responseListData.Msg)
	}

	// 检查 SuccessAdvList 是否为空
	if responseListData.Data.SuccessAdvList == nil || len(responseListData.Data.SuccessAdvList) == 0 {
		errorMsg := "媒体后台未找到该广告账户ID: 未找到该广告账户ID，请切换分配状态查询"
		oeBindBatchTxLogger.Infof("assign_adv_list查询不到广告账户ID:%s", strings.Join(accountID, ","))

		// 发送消息通知
		err := BendiSendText(fmt.Sprintf("%s\n-----------------------------------\n%s", msg.Content, errorMsg), msg.RoomID, msg.Sender)
		if err != nil {
			return nil, err
		}
		return map[string]interface{}{
			"code": 1,
			"msg":  errorMsg,
		}, nil
	}

	// 返回成功结果
	return map[string]interface{}{
		"code": 0,
		"msg":  responseListData.Msg,
		"data": responseListData.Data.SuccessAdvList,
	}, nil
}

// SendCurlRequest 发送HTTP请求
func (s *OeBindBatchService) SendCurlRequest(url string, postData interface{}, xhsCookies string, method string, oeCsrfToken string, result interface{}) error {
	// 创建请求上下文
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// 序列化POST数据
	var bodyReader io.Reader
	if postData != nil {
		jsonData, err := json.Marshal(postData)
		if err != nil {
			return fmt.Errorf("JSON序列化失败: %v", err)
		}
		bodyReader = bytes.NewBuffer(jsonData)
	}

	// 创建请求
	req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
	if err != nil {
		return fmt.Errorf("创建请求失败: %v", err)
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	req.Header.Set("Cookie", xhsCookies)
	if oeCsrfToken != "" {
		req.Header.Set("Cg-Csrf-Token", oeCsrfToken)
	}

	// 创建自定义客户端
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("请求失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("读取响应失败: %v", err)
	}

	oeBindBatchTxLogger.Info("获取后得参数格式：", string(respBody))

	if result != nil {
		if err := json.Unmarshal(respBody, &result); err != nil {
			return fmt.Errorf("JSON解析失败: %v", err)
		}
	}
	return nil
}

// analyzeContent 解析内容为广告主信息数组
func (s *OeBindBatchService) analyzeContent(content []string) (*AnalyzeContentResult, error) {
	// 初始化结果变量
	var accountIDs []string
	var personCharge string
	var collaborator []string
	var subjectNames []string
	var table string = "view_oe_account"

	// 编译正则表达式（支持中文逗号、顿号）
	sepRegex, err := regexp.Compile(`[,，、]`)
	if err != nil {
		oeBindBatchTxLogger.Error("广告主ID分隔符正则表达式编译失败", err)
		return nil, fmt.Errorf("正则表达式编译失败: %w", err)
	}

	// 编译控制字符正则表达式（移除ASCII控制字符）
	controlCharRegex := regexp.MustCompile(`[\x00-\x1F\x7F-\x9F]`)

	// 遍历内容行
	for _, line := range content {
		// 广告主ID
		if strings.HasPrefix(line, "广告主ID:") {
			raw := strings.TrimPrefix(line, "广告主ID:")
			ids := sepRegex.Split(raw, -1)
			for _, id := range ids {
				trimmed := strings.TrimSpace(id)
				if trimmed != "" {
					accountIDs = append(accountIDs, trimmed)
				}
			}
		}
		// 负责人
		if strings.HasPrefix(line, "负责人:") {
			personCharge = strings.TrimSpace(strings.TrimPrefix(line, "负责人:"))
		}
		// 项目名称
		if strings.HasPrefix(line, "项目名称:") {
			lineContent := strings.TrimSpace(strings.TrimPrefix(line, "项目名称:"))
			// 移除控制字符
			lineContent = controlCharRegex.ReplaceAllString(lineContent, "")
			// 分割项目名称
			subject := sepRegex.Split(lineContent, -1)

			oeBindBatchTxLogger.Infof("preg_split result: %v", subject)

			for _, v := range subject {
				trimmed := strings.TrimSpace(v)
				if trimmed != "" {
					subjectNames = append(subjectNames, trimmed)
				}
			}
		}
		// 巨量类型
		if strings.HasPrefix(line, "巨量类型:") {
			oeType := strings.TrimSpace(strings.TrimPrefix(line, "巨量类型:"))
			// 不为空才校验
			if oeType != "" {
				// 校验类型
				if !Contains([]string{"ad", "千川", "本地推"}, oeType) {
					return nil, fmt.Errorf("巨量类型错误，请重新输入 ad/千川/本地推")
				}
				// 设置表名
				table = s.getOETypeTable(oeType)
			}
		}
		// 协作者
		if strings.HasPrefix(line, "协作者:") {
			raw := strings.TrimPrefix(line, "协作者:")
			emails := sepRegex.Split(raw, -1)
			for _, email := range emails {
				trimmed := strings.TrimSpace(email)
				if trimmed != "" {
					collaborator = append(collaborator, trimmed)
				}
			}
		}
	}

	// 记录解析的项目名称
	oeBindBatchTxLogger.Infof("解析项目名称: %v", subjectNames)

	// 如果有项目名称，从数据库获取账户ID
	if len(subjectNames) > 0 {
		// 查询数据库
		var dbAccountIDs []string
		err := common.DBDk.Table(table).
			Where("is_old = 1").
			Where("company IN (?)", subjectNames).
			Pluck("account_id", &dbAccountIDs).Error

		if err != nil {
			oeBindBatchTxLogger.Errorf("数据库查询失败: %v", err)
			return nil, errors.New("未查询到广告账户ID")
		}

		// 合并并去重
		accountIDs = UniqueStrings(append(accountIDs, dbAccountIDs...))
	}

	// 验证必要字段
	if len(accountIDs) == 0 {
		oeBindBatchTxLogger.Warn("未解析到有效广告主ID")
		return nil, fmt.Errorf("解析参数失败: 缺少广告账户ID")
	}

	// 返回结果
	return &AnalyzeContentResult{
		AccountIDs:   accountIDs,
		PersonCharge: personCharge,
		Collaborator: collaborator,
		Table:        table,
	}, nil
}

// getOETypeTable 根据巨量类型获取表名
func (s *OeBindBatchService) getOETypeTable(oeType string) string {
	// 这里实现您的表名映射逻辑
	// 例如：
	tableMap := map[string]string{
		"ad":  "import_oead",
		"千川":  "import_oeqc",
		"本地推": "import_oelocal",
	}

	if table, ok := tableMap[oeType]; ok {
		return table
	}

	return "view_oe_account"
}

// chunkStrings 将字符串切片分割为指定大小的块
func chunkStrings(slice []string, size int) [][]string {
	if size <= 0 {
		return [][]string{slice} // 如果大小为0或负数，返回原始切片
	}

	var chunks [][]string
	for i := 0; i < len(slice); i += size {
		end := i + size
		if end > len(slice) {
			end = len(slice)
		}
		chunks = append(chunks, slice[i:end])
	}

	return chunks
}

func toStringSlice(v interface{}) []string {
	if v == nil {
		return nil
	}

	// 处理map[string]bool类型
	if m, ok := v.(map[string]bool); ok {
		res := make([]string, 0, len(m))
		for k := range m {
			res = append(res, k)
		}
		return res
	}

	if arr, ok := v.([]interface{}); ok {
		res := make([]string, len(arr))
		for i, val := range arr {
			res[i] = fmt.Sprintf("%v", val)
		}
		return res
	}
	return nil
}
